<template>
	<view class="page">
		<!-- 导航栏 -->
		<!-- <view class="nav-bar">
			<view class="nav-title">📊 历史查询记录</view>
		</view> -->
		
		<!-- 主内容 -->
		<view class="content">
			<!-- 统计卡片 -->
			<view class="stats-card">
				<view class="stats-title">
					<text>📈 查询统计</text>
				</view>
				<view class="stats-number">{{ historyList.length }}</view>
				<view class="stats-label">已查询股票数量</view>
			</view>
			
			<!-- 搜索栏 -->
			<view class="search-bar">
				<text class="search-icon">🔍</text>
				<input 
					type="text" 
					class="search-input" 
					v-model="searchKeyword"
					@input="onSearchInput"
					placeholder="搜索股票名称或代码"
				/>
				<view v-if="searchKeyword" class="clear-search" @click="clearSearch">
					<text>✕</text>
				</view>
			</view>
			
			<!-- 历史记录列表 -->
			<view v-if="filteredList.length > 0" class="history-list">
				<view 
					v-for="(item, index) in filteredList" 
					:key="index"
					class="history-item"
					@click="goToQuery(item)"
				>
					<view class="item-header">
						<view class="stock-info-header">
							<view class="stock-icon">
								<text>📈</text>
							</view>
							<view>
								<view class="stock-name">{{ item.stockName }}</view>
								<view class="stock-code">{{ item.stockCode }}</view>
							</view>
						</view>
						<view class="stock-price-main">
							<view 
								class="current-price"
								:class="item.priceChange >= 0 ? 'positive' : 'negative'"
							>
								¥{{ item.lastPrice.toFixed(2) }}
							</view>
							<view 
								class="price-change"
								:class="item.priceChange >= 0 ? 'positive' : 'negative'"
							>
								<text>{{ item.priceChange >= 0 ? '▲' : '▼' }}</text>
								<text>{{ Math.abs(item.priceChangePercent).toFixed(2) }}%</text>
							</view>
						</view>
					</view>
					
					<view class="data-grid">
						<view class="data-item">
							<view class="data-label">昨日开盘</view>
							<view class="data-value">{{ item.todayPrice.toFixed(2) }}</view>
						</view>
						<view class="data-item">
							<view class="data-label">昨日收盘</view>
							<view class="data-value">{{ item.yesterPrice.toFixed(2) }}</view>
						</view>
						<view class="data-item">
							<view class="data-label">市盈率</view>
							<view class="data-value">{{ item.peRatio || '--' }}</view>
						</view>
						<view class="data-item">
							<view class="data-label">成交量</view>
							<view class="data-value">{{ formatVolume(item.volume) }}</view>
						</view>
						<view class="data-item">
							<view class="data-label">成交额</view>
							<view class="data-value">{{ formatTurnover(item.turnover) }}</view>
						</view>
						<view class="data-item">
							<view class="data-label">总市值</view>
							<view class="data-value">{{ formatMarketCap(item.totalMarketValue) }}</view>
						</view>
					</view>
					
					<view class="bottom-row">
						<view class="time-tag">
							<text class="time-icon">🕐</text>
							<text>{{ formatQueryTime(item.queryTime) }}</text>
						</view>
						<view class="delete-btn" @click.stop="deleteHistory(item)">
							<text class="delete-icon">🗑️</text>
							<text class="delete-text">删除</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view v-else class="empty-state">
				<text class="empty-icon">📊</text>
				<text class="empty-text">{{ searchKeyword ? '未找到相关股票' : '暂无查询记录' }}</text>
				<text class="empty-subtext">{{ searchKeyword ? '换个关键词试试' : '开始查询股票吧' }}</text>
			</view>
		</view>
		
		<!-- 底部TabBar -->
		<view class="tab-bar">
			<view class="tab-bar-item" @click="goBack">
				<text class="tab-bar-icon">🏠</text>
				<text class="tab-bar-label">查询</text>
			</view>
			<view class="tab-bar-item active">
				<text class="tab-bar-icon">📝</text>
				<text class="tab-bar-label">历史</text>
			</view>
		</view>
	</view>
</template>

<script>
import storage from '../../utils/storage.js';

export default {
	data() {
		return {
			historyList: [],
			searchKeyword: '',
			filteredList: []
		};
	},
	
	onLoad() {
		this.loadHistory();
	},
	
	onShow() {
		// 每次显示时刷新列表
		this.loadHistory();
	},
	
	methods: {
		/**
		 * 加载历史记录
		 */
		loadHistory() {
			this.historyList = storage.getHistory();
			this.filteredList = this.historyList;
		},
		
		/**
		 * 搜索输入处理
		 * 根据股票名称或代码过滤列表
		 */
		onSearchInput() {
			const keyword = this.searchKeyword.toLowerCase().trim();
			
			if (!keyword) {
				this.filteredList = this.historyList;
				return;
			}
			
			this.filteredList = this.historyList.filter(item => {
				const stockName = (item.stockName || '').toLowerCase();
				const stockCode = (item.stockCode || '').toLowerCase();
				return stockName.includes(keyword) || stockCode.includes(keyword);
			});
		},
		
		/**
		 * 清除搜索
		 */
		clearSearch() {
			this.searchKeyword = '';
			this.filteredList = this.historyList;
		},
		
		/**
		 * 跳转到查询页面并恢复查询参数
		 * @param {Object} item - 历史记录项
		 */
		goToQuery(item) {
			// 保存选中的股票信息和查询参数
			storage.saveSelectedStock({
				stockCode: item.stockCode,
				stockName: item.stockName,
				stockNumber: item.stockNumber,
				queryParams: item.queryParams
			});
			
			// 返回首页
			uni.navigateBack({
				delta: 1
			});
		},
		
		/**
		 * 格式化查询时间
		 * @param {Number} timestamp - 时间戳
		 * @returns {String} 格式化后的时间
		 */
		formatQueryTime(timestamp) {
			if (!timestamp) return '--';
			
			const date = new Date(timestamp);
			const now = new Date();
			const diffMs = now - date;
			const diffMins = Math.floor(diffMs / 60000);
			const diffHours = Math.floor(diffMs / 3600000);
			const diffDays = Math.floor(diffMs / 86400000);
			
			if (diffMins < 1) {
				return '刚刚';
			} else if (diffMins < 60) {
				return `${diffMins}分钟前`;
			} else if (diffHours < 24) {
				return `${diffHours}小时前`;
			} else if (diffDays < 7) {
				return `${diffDays}天前`;
			} else {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hour = String(date.getHours()).padStart(2, '0');
				const minute = String(date.getMinutes()).padStart(2, '0');
				return `${year}-${month}-${day} ${hour}:${minute}`;
			}
		},
		
		/**
		 * 格式化成交量
		 * @param {Number} volume - 成交量
		 * @returns {String} 格式化后的成交量
		 */
		formatVolume(volume) {
			if (!volume && volume !== 0) return '--';
			
			if (volume >= 100000000) {
				return (volume / 100000000).toFixed(2) + '亿';
			} else if (volume >= 10000) {
				return (volume / 10000).toFixed(2) + '万';
			}
			return volume.toFixed(2);
		},
		
		/**
		 * 格式化成交额
		 * @param {Number} turnover - 成交额（元）
		 * @returns {String} 格式化后的成交额
		 */
		formatTurnover(turnover) {
			if (!turnover && turnover !== 0) return '--';
			
			if (turnover >= 100000000) {
				return (turnover / 100000000).toFixed(2) + '亿';
			} else if (turnover >= 10000) {
				return (turnover / 10000).toFixed(2) + '万';
			}
			return turnover.toFixed(2);
		},
		
		/**
		 * 格式化总市值
		 * @param {Number} marketValue - 总市值（元）
		 * @returns {String} 格式化后的总市值
		 */
		formatMarketCap(marketValue) {
			if (!marketValue && marketValue !== 0) return '--';
			
			if (marketValue >= 1000000000000) {
				return (marketValue / 1000000000000).toFixed(2) + '万亿';
			} else if (marketValue >= 100000000) {
				return (marketValue / 100000000).toFixed(2) + '亿';
			} else if (marketValue >= 10000) {
				return (marketValue / 10000).toFixed(2) + '万';
			}
			return marketValue.toFixed(2);
		},
		
		/**
		 * 删除历史记录
		 * @param {Object} item - 要删除的历史记录项
		 */
		deleteHistory(item) {
			uni.showModal({
				title: '确认删除',
				content: `确定要删除 ${item.stockName} (${item.stockCode}) 的查询记录吗？`,
				success: (res) => {
					if (res.confirm) {
						// 删除记录
						storage.removeHistory(item.stockCode);
						// 重新加载列表
						this.loadHistory();
						// 提示删除成功
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
					}
				}
			});
		},
		
		/**
		 * 返回首页
		 */
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		}
	}
};
</script>

<style scoped>
.page {
	background: #f5f5f7;
	min-height: 100vh;
	overflow-x: hidden;
}

/* 导航栏 */
.nav-bar {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 15px 20px 20px;
	color: white;
}

.nav-title {
	font-size: 28px;
	font-weight: 700;
	text-align: center;
}

/* 内容区域 */
.content {
	padding: 12px;
	padding-bottom: 100px;
}

/* 统计卡片 */
.stats-card {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 16px;
	padding: 15px;
	color: white;
	margin-bottom: 12px;
	box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.stats-title {
	font-size: 13px;
	opacity: 0.9;
	margin-bottom: 6px;
}

.stats-number {
	font-size: 32px;
	font-weight: 700;
}

.stats-label {
	font-size: 13px;
	opacity: 0.8;
	margin-top: 3px;
}

/* 搜索栏 */
.search-bar {
	background: white;
	border-radius: 12px;
	padding: 10px 12px;
	display: flex;
	align-items: center;
	gap: 8px;
	margin-bottom: 12px;
	box-shadow: 0 2px 10px rgba(0,0,0,0.05);
	position: relative;
}

.search-icon {
	font-size: 15px;
}

.search-input {
	flex: 1;
	border: none;
	outline: none;
	font-size: 14px;
	background: transparent;
}

.clear-search {
	width: 20px;
	height: 20px;
	background: #ccc;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	font-size: 12px;
}

/* 历史记录列表 */
.history-list {
	display: flex;
	flex-direction: column;
	gap: 10px;
}

.history-item {
	background: white;
	border-radius: 12px;
	padding: 12px;
	box-shadow: 0 2px 10px rgba(0,0,0,0.05);
	transition: all 0.3s;
	border: 2px solid transparent;
}

.history-item:active {
	transform: scale(0.98);
	border-color: #667eea;
}

.item-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
}

.stock-info-header {
	display: flex;
	align-items: center;
	gap: 8px;
}

.stock-icon {
	width: 36px;
	height: 36px;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 8px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
}

.stock-name {
	font-size: 16px;
	font-weight: 700;
	color: #333;
}

.stock-code {
	font-size: 12px;
	color: #6b7280;
	margin-top: 2px;
}

.stock-price-main {
	text-align: right;
}

.current-price {
	font-size: 18px;
	font-weight: 700;
}

.current-price.positive {
	color: #ef4444;
}

.current-price.negative {
	color: #10b981;
}

.price-change {
	font-size: 12px;
	margin-top: 2px;
}

.price-change.positive {
	color: #ef4444;
}

.price-change.negative {
	color: #10b981;
}

/* 数据网格 */
.data-grid {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 6px;
}

.data-item {
	background: #f9fafb;
	padding: 6px 8px;
	border-radius: 8px;
}

.data-label {
	font-size: 10px;
	color: #6b7280;
	margin-bottom: 3px;
}

.data-value {
	font-size: 13px;
	font-weight: 600;
	color: #333;
}

/* 底部行 */
.bottom-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: 8px;
}

/* 时间标签 */
.time-tag {
	display: inline-flex;
	align-items: center;
	gap: 4px;
	background: #f3f4f6;
	padding: 4px 8px;
	border-radius: 6px;
	font-size: 10px;
	color: #6b7280;
}

/* 删除按钮 */
.delete-btn {
	display: flex;
	align-items: center;
	gap: 4px;
	padding: 4px 8px;
	border-radius: 6px;
	background: #fee2e2;
	color: #ef4444;
	font-size: 10px;
	transition: all 0.3s;
}

.delete-btn:active {
	opacity: 0.8;
	transform: scale(0.95);
}

.delete-icon {
	font-size: 12px;
}

.delete-text {
	font-weight: 500;
}

.time-icon {
	font-size: 10px;
}

/* 空状态 */
.empty-state {
	text-align: center;
	padding: 60px 20px;
	color: #9ca3af;
}

.empty-icon {
	font-size: 60px;
	display: block;
	margin-bottom: 15px;
	opacity: 0.5;
}

.empty-text {
	font-size: 16px;
	margin-bottom: 5px;
	display: block;
}

.empty-subtext {
	font-size: 14px;
	opacity: 0.8;
	display: block;
}

/* 底部TabBar */
.tab-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: white;
	display: flex;
	justify-content: space-around;
	padding: 8px 0 20px;
	border-top: 1px solid #e5e7eb;
	box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
}

.tab-bar-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 4px;
	color: #9ca3af;
}

.tab-bar-item.active {
	color: #667eea;
}

.tab-bar-icon {
	font-size: 22px;
}

.tab-bar-label {
	font-size: 10px;
	font-weight: 500;
}
</style>

